import java.util.*;
import java.util.stream.Collectors;

/**
 * 对于每一个单词，计算字母组成，再和其他对比，n*n
 * 改进：算法  先排序、再比较字符串是否相同 --> 选用List、Map 避免遍历
 */
public class LCP49 {
    public static void main(String[] args) {
//        String strs1 = '["eat", "tea", "tan", "ate", "nat", "bat"]';
        String strs2 = "['eat', 'tea', 'tan', 'ate', 'nat', 'bat']";
        String strs3 = "['']";
        String strs4 = "['a']";
//        String[] strArr1 = ["eat", "tea", "tan", "ate", "nat", "bat"];
//        String[] strArr2 = [""];
//        String[] strArr3 = ["a"];
        String[] strArr1 = {"eat", "tea", "tan", "ate", "nat", "bat"};    //字符串数组用{}表示
        String[] strArr2 = {""};
        String[] strArr3 = {"a"};

        List<List<String>> groupResult = groupAnagrams(strArr1);
        System.out.println(groupResult);
        System.out.println(groupAnagrams(strArr2));
        System.out.println(groupAnagrams(strArr3));
    }

    //方法一 排序
//    public static List<List<String>> groupAnagrams(String[] strs) {
//        Map<String, List<String>> map = new HashMap<String, List<String>>();
//        for (String s : strs) {    //O(nklogk)
//            char[] array = s.toCharArray();
//            Arrays.sort(array);  //快速排序
//            String key = new String(array);
//            List<String> list = map.getOrDefault(key, new ArrayList<String>());
//            list.add(s);
//            map.put(key, list);
//        }
//
//        return new ArrayList<List<String>>(map.values());
//    }

    //
    public static List<List<String>> groupAnagrams(String[] strs) {
        return new ArrayList<>(Arrays.stream(strs).collect(Collectors.groupingBy(s -> Arrays.toString(s.codePoints().sorted().toArray()))).values());
    }

    //方法二 计数   单词数作为哈希表的主键
}
